package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;

import static java.lang.Integer.parseInt;


/**
 * Created with IntelliJ IDEA.
 * User: Thoughtworker
 * Date: 10/9/13
 * Time: 11:03 AM
 * To change this template use File | Settings | File Templates.
 */
public class Menu {
    private final PrintStream printStream;
    private Library library;
    private BufferedReader bufferReader;
    public boolean exit;
    private LoginHandler loginHandler;

    //private Map<Integer, Command> commandMap;


    public Menu(PrintStream printStream, Library library , BufferedReader reader , LoginHandler loginHandler) {
        this.printStream = printStream;
        this.bufferReader = reader;
        this.library = library;
        this.loginHandler = loginHandler;
    }



    public void printMenuOptions() {
        String outputString = "";
        for (Options currentOption: Options.values()) {
            outputString += currentOption.id + " " + currentOption.optionName + "\n";

        }
        printStream.print(outputString);
    }

    public int readUserOption() throws IOException {

        int userOption ;

        try {
            String s = bufferReader.readLine();
            userOption = parseInt(s) ;
            if(userOption <= 0 ||( userOption > Options.values().length && userOption !=Options.EXIT.id))
                throw new Exception();
        } catch (Exception e) {
            printStream.println("Select a valid option!!");
            userOption = 0;
        }

        return userOption;

    }

    public void executeSelectedOption(int selectedOption) throws IOException {
       // commandMap.get(selectedOption).execute();


        if(selectedOption == Options.LISTBOOKS.id){
            library.printListOfAllBooks();
        }else if (selectedOption ==Options.RESERVEBOOK.id){
            printStream.println("Please type in the book id for the book you want to reserve");
            library.printListOfAllBooks();
            library.reserveBook(readUserOption());

        }else if(selectedOption == Options.CHECKMEMBERSHIP.id){
            loginHandler.checkMembership();
        }else if (selectedOption == Options.VIEWMOVIES.id){
            library.printListOfMovies();

        }else if(selectedOption == Options.EXIT.id){
            exit = true;
        }
    }



}
